package tulingxueyuan117;

/**
 * Author: Zhang Dongwei
 * Date: 2022/10/19 16:38
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class p11_合并两个有序链表_21_re {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode a1 = new ListNode(2);
        ListNode a2 = new ListNode(4);
        l1.next = a1;
        a1.next = a2;
        ListNode l2 = new ListNode(1);
        ListNode b1 = new ListNode(3);
        ListNode b2 = new ListNode(4);
        l2.next = b1;
        b1.next = b2;

        ListNode res = mergeTwoLists(l1, l2);
        while (res!=null){
            System.out.println(res.val);
            res = res.next;
        }
    }

    public static ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if(list1==null) return list2;
        if(list2==null) return list1;
        ListNode res = null;
        if(list1.val <= list2.val){
            res = list1;
            res.next = mergeTwoLists(list1.next, list2);
        }else {
            res = list2;
            res.next = mergeTwoLists(list1, list2.next);
        }
        return res;
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1==null) return list2;
        if(list2==null) return list1;
        ListNode res = new ListNode(0);
        ListNode p = res;
        while (list1!=null&&list2!=null){
            if(list1.val<list2.val){
                p.next = list1;
                list1 = list1.next;
            }else {
                p.next = list2;
                list2 = list2.next;
            }
            p = p.next;
        }
        if(list1 != null) p.next = list1;
        if(list2 != null) p.next = list2;
        return res.next;
    }
}
